<template>
    <div>
        <el-form :inline="true" :model="condition" class="search-form" label-width="120px">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="作业港口">
                        <select-port v-model="allPortCodes"
                                     :name="allPortCodes" :isMultiple = "true"></select-port>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="作业日期起">
                        <el-date-picker v-model="condition['search_GTE_jobTime']"
                                        :picker-options="startPickerOptions" type="date" placeholder="起始日期"
                                        format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="作业日期止">
                        <el-date-picker v-model="condition['search_LTE_jobTime']"
                                        :picker-options="endPickerOptions" type="date" placeholder="结束日期"
                                        format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-button class="ml-120" @click="loadData">查 询</el-button>
                    <el-button v-if="power('TALLY_PIECE_GROUP')" @click="handleSee(false)">作业班组明细</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-row type="flex" justify="center">
            <div id="pie" @mouseenter="onChartClickPie" @mouseleave="offChartClickPie" class="classCount-style"></div>
            <div id="bar" @mouseenter="onChartClickBar" @mouseleave="offChartClickBar" class="classCount-style"></div>
        </el-row>
        <el-row type="flex" v-if="table.length>0">
            <el-table :data="table" border stripe show-summary :summary-method="getSummary" style="width: 50%"
                      max-height="500"
                      class="mt-10">
                <el-table-column label="序号" min-width="55">
                    <template slot-scope="scope">
                        <div>{{ scope.$index + 1 }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="portName" label="作业港口"  min-width="120"></el-table-column>
                <el-table-column prop="teamName" label="作业班组"  min-width="120"></el-table-column>
                <el-table-column prop="time" label="工时"  min-width="100"></el-table-column>
                <el-table-column align="center" label="操作"  width="120">
                    <template slot-scope="scope">
                        <el-button v-if="power('TALLY_PIECE_GROUP')" size="small" type="text"
                                   @click="handleSee(true,scope.row)">
                            班组统计
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div id="smallPie" class="class-count-small-pie"></div>
        </el-row>
    </div>
</template>

<script>
    import { getClassCountPie, getClassCountBar, getClassCount } from "@/api/balance/balance";
    import { getLocalTime } from "@/utils/dateFormat";
    import selectPort from '@/components/select/selectPort'

    // 引入基本模板
    let echarts = require("echarts/lib/echarts");
    import "echarts/theme/macarons";
    // 引入柱状图组件
    require("echarts/lib/chart/bar");
    // 引入提示框和title组件
    require("echarts/lib/component/tooltip");
    require("echarts/lib/component/title");
    require("echarts/lib/chart/line");
    require("echarts/lib/chart/pie");
    export default {
        name: "港口日期班组统计",
        components: { selectPort },
        data() {
            return {
                condition: {
                    search_EQ_portCode: '',
                    search_GTE_jobTime: '',
                    search_LTE_jobTime: ''
                },
                pie: '',
                smallPie: '',
                bar: '',
                tableForm: {
                    search_LIKE_portName: '',
                    search_GTE_jobTime: '',
                    search_LTE_jobTime: ''
                },
                table: [],
                allPortCodes:''
            }
        },
        mounted() {
            let classCountIndex = JSON.parse(sessionStorage.getItem('classCountIndex'))
            this.condition["search_GTE_jobTime"] = classCountIndex.date
            this.condition["search_LTE_jobTime"] = classCountIndex.date
            let portNew = classCountIndex.port
            const port = JSON.parse(sessionStorage.getItem('SET_PORT'))
            if (port && port.length == 1){
                if (portNew != null && portNew != ""){
                    portNew=[portNew]
                }
            }
            this.$nextTick(() => {
                this.allPortCodes = portNew || ''
                    this.$nextTick(() => {
                        this.loadData()
                    })
            })

        },
        activated() {
            if (!this.created) {
                let classCountIndexNew = JSON.parse(sessionStorage.getItem('classCountIndex'))
                this.condition["search_GTE_jobTime"] = classCountIndexNew.date
                this.condition["search_LTE_jobTime"] = classCountIndexNew.date
                this.loadData()
            }
        },
        methods: {
            loadData() {
                this.created = false
                this.table = []
                this.getPie()
                this.getBar()
            },
            onChartClickPie() {
                if (!this.power('TALLY_PIECE_GROUP')) {
                    return
                }
                this.pie.on('click', (param) => {
                    const { name } = param
                    this.tableForm.search_LIKE_portName = name
                    this.tableForm.search_GTE_jobTime = this.condition["search_GTE_jobTime"]
                    this.tableForm.search_LTE_jobTime = this.condition["search_LTE_jobTime"]
                    this.getData()
                })
            },
            offChartClickPie() {
                this.$nextTick(() => {
                    this.pie.off('click')
                })
            },
            onChartClickBar() {
                if (!this.power('TALLY_PIECE_GROUP')) {
                    return
                }
                this.bar.on('click', (param) => {
                    const { seriesName, name } = param
                    console.log(seriesName, name)
                    this.tableForm.search_LIKE_portName = seriesName
                    this.tableForm.search_GTE_jobTime = this.condition["search_GTE_jobTime"]
                    this.tableForm.search_LTE_jobTime = this.condition["search_LTE_jobTime"]
                    this.getData();
                })
            },
            offChartClickBar() {
                this.$nextTick(() => {
                    this.bar.off('click')
                })
            },
            getData() {
                getClassCount(this.$assist.copySearchConditions(this.tableForm)).then(res => {
                    this.table = res.data.aaData
                    let name = []
                    let pieValue = []
                    for (let i = 0; i < this.table.length; i++) {
                        const el = this.table[i]
                        name.push(el.teamName)
                        pieValue.push({ value: el.time, name: el.teamName })
                    }
                    this.$nextTick(() => {
                        this.smallPie = echarts.init(
                            document.getElementById("smallPie"),
                            "macarons"
                        );
                        this.smallPie.setOption({
                            title: {
                                text: '工时',
                                x: 'center'
                            },
                            tooltip: {
                                trigger: 'item',
                                formatter: "{a} <br/>{b} : {c} ({d}%)"
                            },
                            legend: {
                                orient: 'vertical',
                                left: 'left',
                                data: name
                            },
                            series: [
                                {
                                    // name: '访问来源',
                                    type: 'pie',
                                    radius: '55%',
                                    center: ['50%', '60%'],
                                    data: pieValue,
                                    itemStyle: {
                                        emphasis: {
                                            shadowBlur: 10,
                                            shadowOffsetX: 0,
                                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                                        }
                                    }
                                }
                            ]
                        })
                    })

                })
            },
            getSummary(params) {
                const { columns, data } = params
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 1) {
                        sums[index] = '合计';
                        return;
                    }
                    const values = data.map(item => Number(item[column.property]));
                    if (!values.every(value => isNaN(value)) && column.property === 'time') {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                let prevNum = Number(prev) + Number(curr)
                                return prevNum.toFixed(2);
                            } else {
                                // let prevNum=prev
                                return Number(prev).toFixed(2);
                            }
                        }, 0);
                        sums[index] += ' ';
                    } else {
                        sums[index] = '';
                    }
                });
                return sums;
            },
            getPie() {
                this.condition.search_IN_portCode = this.arrayToString(this.allPortCodes)
                getClassCountPie(this.$assist.copySearchConditions(this.condition)).then(res => {
                    let data = res.data.aaData
                    let name = []
                    let pieValue = []
                    for (let i = 0; i < data.length; i++) {
                        const el = data[i]
                        name.push(el.name)
                        pieValue.push({ value: el.time, name: el.portName })
                    }
                    this.pie = echarts.init(
                        document.getElementById("pie"),
                        "macarons"
                    );
                    this.pie.setOption({
                        title: {
                            text: '港口工时汇总统计',
                            x: 'center'
                        },
                        tooltip: {
                            trigger: 'item',
                            formatter: "{a} <br/>{b} : {c} ({d}%)"
                        },
                        legend: {
                            orient: 'vertical',
                            left: 'left',
                            data: name
                        },
                        series: [
                            {
                                // name: '访问来源',
                                type: 'pie',
                                radius: '55%',
                                center: ['50%', '60%'],
                                data: pieValue,
                                itemStyle: {
                                    emphasis: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]
                    })
                })
            },
            arrayToString:function(arr){
                let value = ""
                if (arr != null && arr != "" && arr.length > 0){
                    arr.forEach((column, index) => {
                        value = value + "," + column
                    })
                    value = value.substring(1)
                }
                return value
            },
            getBar() {
                this.condition.search_IN_portCode = this.arrayToString(this.allPortCodes)
                getClassCountBar(this.$assist.copySearchConditions(this.condition)).then(res => {
                    let data = res.data.aaData
                    let xData = []
                    let lData = []
                    let seriesValue = []
                    for (let i = 0; i < data.length; i++) {
                        const el = data[i]
                        lData.push(el.portCode)
                        let numData = []
                        let dateData = []
                        for (let j = 0; j < el.piecePort.length; j++) {
                            const elData = el.piecePort[j]
                            numData.push(elData.piece)
                            dateData.push(elData.date)

                        }
                        if (i === 0) {
                            xData.push(...dateData)
                        }
                        seriesValue.push({
                            name: el.portCode,
                            type: 'bar',
                            stack: '港口名称',
                            data: numData
                        })
                    }
                    this.bar = echarts.init(
                        document.getElementById("bar"),
                        "macarons"
                    );
                    this.bar.setOption({
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                            }
                        },
                        legend: {
                            data: lData
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: [
                            {
                                type: 'category',
                                data: xData
                            }
                        ],
                        yAxis: [
                            {
                                type: 'value'
                            }
                        ],
                        dataZoom: {
                            show: true,
                            realtime: true,
                            start: 0,
                            end: 100
                        },
                        series: seriesValue
                    })
                })
            },
            handleSee(bool, item) {
                let params = this.$assist.copySearchConditions(this.condition)
                if (bool) {
                    params.search_LIKE_className = item.teamName
                    params.search_EQ_portCode = item.portCode
                }
                sessionStorage.setItem('classCount', JSON.stringify(params))
                this.$router.push({ path: '/work/workClass', name: '作业班组统计' })
            },
            handleChangeEnd(val) {
                let setVal = val;
                if (val) {
                    setVal = val.split(" ")[0] + " 23:59:59";
                }
                this.condition["search_LTE_jobTime"] = setVal;
            },

        },
        computed: {
            startPickerOptions() {
                let endDate = this.condition["search_LTE_jobTime"];
                return {
                    disabledDate(time) {
                        if (endDate) {
                            return time.getTime() > new Date(endDate).getTime();
                        } else {
                            return false;
                        }
                    }
                };
            },
            endPickerOptions() {
                let startDate = this.condition["search_GTE_jobTime"];
                return {
                    disabledDate(time) {
                        if (startDate) {
                            return time.getTime() < new Date(startDate).getTime() - 60 * 60 * 24 * 1000;
                        } else {
                            return false;
                        }
                    }
                };
            },
        },
    }
</script>

<style scoped>
    .classCount-style {
        height: 500px;
        width: 50%;
    }

    .class-count-small-pie {
        width: 50%;
        height: 300px;
    }
</style>
